package com.hup.winHolderService.framework.util.net;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;

/**
 * @author hugan
 * @date 2023/7/11
 */
public class HttpUtil {

    /**
     * 获取request
     *
     * @throws NullPointerException 非请求线程调用时
     */
    public static HttpServletRequest getRequest() {
        return getRequestAttributes().getRequest();
    }

    /**
     * @apiNote 非请求线程调用时, 返回null(如异步执行器)
     */
    public static ServletRequestAttributes getRequestAttributes() {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        return (ServletRequestAttributes) attributes;
    }

    public static String getIpAddr(HttpServletRequest request) {
        return IpUtil.getIpAddr(request);
    }

    public static boolean isAjax(HttpServletRequest request) {
        String accept = request.getHeader("accept");
        if (accept != null && accept.contains("application/json")) return true;

        String xRequestedWith = request.getHeader("X-Requested-With");
        return xRequestedWith != null && xRequestedWith.contains("XMLHttpRequest");
    }

    public static HashMap<String, String> getHeaders(HttpServletRequest request) {
        HashMap<String, String> res = new HashMap<>();
        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            String value = request.getHeader(name);
            res.put(name, value);
        }
        return res;
    }

}
